# -*- coding: utf-8 -*-

# graphic-pppoe-client - Easy graphic networking manager
#
# Author: GoTLiuM InSPiRiT <gotlium@gmail.com>
#
# Copyright 2010, GoTLiuM InSPiRiT <gotlium@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

from models.__init__ import getIfnameByConnId, getConnectionById
from libraries.net import getIfInfo, setIfConfig, setupDhcp, \
	setIfState, getIfState
from time import sleep
from libraries.los import msg

class Ipconfigs(object):
	
	def setIpconfig(self, connId):
		msg("IPConfig: connection id: %s" % connId)
		connection = getConnectionById(connId)

		ifName = connection['if_name']
		ifType = connection['type']
		msg("IPConfig: ifName: %s" % ifName)
		msg("IPConfig: ifType: %s" % ifType)

		if ifType == 'dhcp':
			return setupDhcp(ifName)
		elif ifType == 'manual':
			ips = []
			for row in self.selectIpconfigs(connId):
				ips.append((
					row['ip_address'], row['netmask'], row['gateway']
				))
			return setIfConfig(
				ifName = ifName,
				ips = ips,
				mac = connection['hwaddr'],
				mtu = connection['mtu']
			)
		else:
			if not getIfState(ifName):
				return setIfState(ifName, 1)
			return True
		return False

	def delIpconfig(self, connId):
		ifName = getIfnameByConnId(connId)
		if ifName:
			setIfState(ifName, 0)

	def flushIpConfig(self, connId):
		ifName = getIfnameByConnId(connId)
		if ifName:
			setIfState(ifName, 0)
			sleep(3)
			setIfState(ifName, 1)
			msg("IPConfig: %s flushed" % ifName)
			return True
		return False
